Passing single null
or primitive array argument to the variable arity method may not work as expected. In the case of
null
, it is not passed as array with single element, but the argument itself is null
. In the case of a primitive array, if
the formal parameter is Object...
, it is passed as a single element array. This may not be obvious to someone not familiar with such
corner cases, and it is probably better to avoid such ambiguities by explicitly casting the argument to the desired type.
Noncompliant code example
class A {
public static void main(String[] args) {
vararg(null); // Noncompliant, prints "null"
int[] arr = {1,2,3};
vararg(arr); // Noncompliant, prints "length: 1"
}
static void vararg(Object... s) {
if (s == null) {
System.out.println("null");
} else {
System.out.println("length: " + s.length);
}
}
}
Compliant solution
class A {
public static void main(String[] args) {
vararg((Object) null); // prints 1
Object[] arr = {1,2,3};
vararg(arr); // prints 3
}
static void vararg(Object... s) {
if (s == null) {
System.out.println("null"); // not reached
} else {
System.out.println("length: " + s.length);
}
}
}